/*
 * COPYRIGHT:	2010 Christopher Smith, licenced under the GNU GPL v2; see COPYING in the top level directory
 * PROJECT:		sdedit
 * FILE:		delayed import.cpp
 * PURPOSE:		an on-demand delayed import function class
 *				
 */

template <class T> struct DelayedImportFunction
{
	PCWSTR Lib;
	PCSTR Name;
	T Func;
	DelayedImportFunction(PCWSTR Lib, PCSTR Name) :
		Lib(Lib),
		Name(Name),
		Func(NULL)
	{}

	void DemandQuiet()
	{
		if(!Func)
		{
			HMODULE Module = GetModuleHandle(Lib);

			if(Module)
				Func = c_cast<T>(GetProcAddress(Module, Name));
		}
	}

	void Demand()
	{
		HMODULE Module = GetModuleHandle(Lib);

		RaiseOnWin32ErrorT<HMODULE>(Module);

		Func = c_cast<T>(GetProcAddress(Module, Name));

		if(!Func)
			RaiseWin32Error(ERROR_NOT_SUPPORTED);
	}

	operator T()
	{
		Demand();
		return Func;
	}
};